/* 麻将扎马 */
var MJModel           = require('./MJModel');
var MJProto           = require('./MJProto');
var RoomProto         = require('../../API/RoomProto');

cc.Class({
	extends: cc.Component,
	properties: {
        MaJiangAtlas: cc.SpriteAtlas,
		content: cc.Node,
		item: cc.Node,
		layout: cc.Node,
	},

	onLoad: function () {
		this.node.active = false;
		Global.MessageCallback.addListener('RoomMessagePush', this);
		Global.MessageCallback.addListener('GameMessagePush', this);
	},

	gameInit: function () {
		this.node.active = false;
		/* TEST */
		/* this.showMa({ myMaCards: [
			{card: 1, win: true},
			{card: 1, win: true},
			{card: 1, win: false},
		]});   */
	},

	messageCallbackHandler: function(router, msg) {
		if(!MJModel.getGameInited()) { return; }
		if (router === 'RoomMessagePush') {
			if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
				this.gameInit();
			}
		}
		else if(router === 'GameMessagePush') {
			if(msg.type === MJProto.GAME_RESULT_PUSH && msg.data.result.winChairIDArray.length != 0) {
				this.showMa(msg.data.result);
			}
		}
	},

	showMa: function (result) {
		this.node.active = true;
		this.unscheduleAllCallbacks();
		for (let node of this.content.children) {
			node.destroy();
		}
		for (let node of this.layout.children) {
			node.destroy();
		}
		let cards = result.myMaCards.slice();
		let nodeArray = [];
		for (let i = 0; i < cards.length; ++i) {
			let node = cc.instantiate(this.item);
			node.parent = this.content;
			node.active = true;
			nodeArray.push(node);
		}
		this.schedule(() => {
			if (nodeArray.length > 0) {
				let node = nodeArray.shift();
				let card = cards.shift();
				let name = "down2_"+Math.floor(card.card/10)+"_"+(card.card%10);
				node.getComponent(cc.Sprite).spriteFrame = this.MaJiangAtlas.getSpriteFrame(name);
				if (card.win) {
					node.runAction(cc.sequence([
						cc.scaleTo(0.05, 1.3),
						cc.scaleTo(0.05, 1.1),
						cc.callFunc(() => {
							cc.find('win', node).active = true;
						})
					]));
				}
			}
		}, 0.2, cards.length);
		this.scheduleOnce(() => {
			this.node.active = false;
		}, 3); 
	},

	onDestroy: function () {
		Global.MessageCallback.removeListener('RoomMessagePush', this);
		Global.MessageCallback.removeListener('GameMessagePush', this);
	},
});

